package com.ruitu.mall_98_1.product.adapter;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruitu.mall_98_1.R;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.product.Sku;
import com.ruitu.router_module.bean.product.Spec;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

//只能从上往下选 没有bug
public class SpecApter extends ListBaseAdapter<Spec> {
    private List<Sku> skuList = new ArrayList<>();//套餐形式的规格
    private int modelNum = 1;//规格的数量
    private boolean[] isSelects;//记录是否已选规格(主要记录上一级是否已选)
    public String mDataListJson = "";

    public void setSkuList(List<Sku> skuList) {
        this.skuList = skuList;
    }

    public SpecApter(Context context) {
        super(context);
    }

    @Override
    public void setDataList(Collection<Spec> list) {
        super.setDataList(list);
        modelNum = mDataList.size();
        isSelects = new boolean[modelNum];
        for (int i = 0; i < isSelects.length; i++) {
            isSelects[i] = false;
        }
    }

    //找到最小的已选择的位置(最上方的位置)
    private int findMaxAvailable() {
        for (int i = isSelects.length - 1; i >= 0; i--) {
            if (isSelects[i]) {
                return i;
            }
        }
        return -1;
    }

    private void resetData() {
        mDataList.clear();
        mDataList = new Gson().fromJson(mDataListJson, new TypeToken<List<Spec>>() {
        }.getType());//恢复数据
        for (int i = 0; i < isSelects.length; i++) {
            isSelects[i] = false;
        }
        Arad.bus.post(new EventModel(18110951, null));//通知外层对话框更新数据
    }

    //下一个规格是否选中了
    private boolean isNextSpecSelected(int currPos) {
        Spec nextSpec = mDataList.get(currPos + 1);
        for (int i = 0; i < nextSpec.getGoodsFeatureVals().size(); i++) {
            Spec.SpecDetail detail = nextSpec.getGoodsFeatureVals().get(i);
            if (detail.isSelected()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getLayoutId() {
        return R.layout.pro_item_spec;
    }

    @Override
    public void onBindItemHolder(SuperViewHolder holder, final int pos) {
        TextView tv_name = holder.getView(R.id.tv_name);
        RecyclerView rcv_val = holder.getView(R.id.rcv_val);

        final Spec spec = mDataList.get(pos);
        tv_name.setText(spec.getGoodsFeatureName());

        final List<Spec.SpecDetail> valList1 = spec.getGoodsFeatureVals();
        try {
            Logg.i("adapter中valList1.size = " + valList1.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        final ValAdapter valAdapter = new ValAdapter(mContext);
        GridLayoutManager manager = new GridLayoutManager(mContext, 3);
        rcv_val.setLayoutManager(manager);
        rcv_val.setAdapter(valAdapter);
        valAdapter.setDataList(valList1);
        valAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int selectPos) {
                List<Spec.SpecDetail> valList = new ArrayList<>();
                if (pos > 0 && !isSelects[pos - 1]) {//当前点击规格的上一级还没有选择
                    ToastUtils.showShort("请先选择" + mDataList.get(pos - 1).getGoodsFeatureName());
                    isSelects[pos] = false;
                    for (int a = 0; a < valList.size(); a++) {
                        valList.get(a).setSelected(false);
                    }
                } else {//选择第一个规格的时候 pos = 0 重置之前选择的数据
                    if (pos == 0) {
                        resetData();
                    }

                    valList = mDataList.get(pos).getGoodsFeatureVals();

                    for (int i = pos; i < isSelects.length; i++) {
                        //当前和之前的选择位置标记为true,后面的标记为false
                        if (i == pos) {
                            isSelects[i] = true;
                        } else {
                            isSelects[i] = false;
                        }
                    }
                    for (int a = 0; a < valList.size(); a++) {
                        if (a == selectPos) {
                            valList.get(a).setSelected(true);
                        } else {
                            valList.get(a).setSelected(false);
                        }
                    }

                    //点击的中间位置,相当于重复选择的(因为该规格的下一项已经被选中)
                    if (pos > 0 && pos < mDataList.size() - 1 && isNextSpecSelected(pos)) {
                        resetData();
                        ToastUtils.showShort("请先选择" + mDataList.get(pos - 1).getGoodsFeatureName());
                    }
                    //点击的中间位置,(该规格的下一项还没有选中,此时应当重置后面的规格数据
                    if (pos > 0 && pos < mDataList.size() - 1 && !isNextSpecSelected(pos)) {
                        List<Spec> oldDataList = new Gson().fromJson(mDataListJson, new TypeToken<List<Spec>>() {
                        }.getType());//最原始的数据
                        for (int c = pos + 1; c < mDataList.size(); c++) {
                            mDataList.get(c).setGoodsFeatureVals(oldDataList.get(c).getGoodsFeatureVals());
                        }
                    }
                }

                int maxAvailable = findMaxAvailable();
                StringBuffer selectedSpecAndVal = new StringBuffer("");//specId1:valId1,specId2:valId2,
                if (maxAvailable != -1) {//说明有选中的
                    for (int x = 0; x <= maxAvailable; x++) {
                        String selectedSpecId = mDataList.get(x).getId();//选中的规格id
                        List<Spec.SpecDetail> tmpValList = mDataList.get(x).getGoodsFeatureVals();
                        for (int y = 0; y < tmpValList.size(); y++) {
                            if (tmpValList.get(y).isSelected()) {
                                String selectedValId = tmpValList.get(y).getId();//选中的值的id
                                selectedSpecAndVal.append(selectedSpecId + ":" + selectedValId + ",");
                            }
                        }
                    }
                }

                String tmpStr = selectedSpecAndVal.toString();
                Logg.i("tmpStr = " + tmpStr);
                if (!TextUtils.isEmpty(tmpStr) && tmpStr.contains(",")) {
                    String txt = tmpStr.substring(0, tmpStr.lastIndexOf(","));
                    if (maxAvailable >= isSelects.length - 1) {//说明都选择完毕了
                        Logg.i("规格选择完成了");
                        //将选择的skuId的值传出去
                        for (int i = 0; i < skuList.size(); i++) {
                            boolean isSkuId = true;//是否是选择的skuId
                            String skuSpecValSet = skuList.get(i).getSkuInfo();
                            String[] txtArr = txt.split(",");
                            for (int j = 0; j < txtArr.length; j++) {
                                if (!skuSpecValSet.contains(txtArr[j])) {
                                    isSkuId = false;
                                }
                            }
                            if (isSkuId) {
                                Logg.i("规格选择完成的id = " + skuList.get(i).getId());
                                Arad.bus.post(new EventModel(18110951, skuList.get(i)));
                            }
                        }
                    } else {//还没有选择完毕
                        Arad.bus.post(new EventModel(18110951, null));

                        List<Spec.SpecDetail> nextValList = new ArrayList<>();
                        int selectIndex = findMaxAvailable();//已经选择的规格数量

                        for (int i = 0; i < skuList.size(); i++) {//遍历套餐列表
                            String skuSpecValSet = skuList.get(i).getSkuInfo();
                            String[] skuSpecValArr = skuList.get(i).getSkuInfo().split(",");

                            String nextSpecId = mDataList.get(selectIndex + 1).getId();//下一步需要选择的规格id
                            String[] selectSpecValArr = txt.split(",");
                            boolean isCurrSetOk = true;

                            for (int n = 0; n < selectSpecValArr.length; n++) {//遍历选中的每一条规格,值
                                if (skuSpecValSet.contains(selectSpecValArr[n])) {
                                    continue;
                                } else {
                                    isCurrSetOk = false;
                                }
                            }
                            if (isCurrSetOk) {//说明当前套餐匹配已选中的规格和值
                                for (int m = 0; m < skuSpecValArr.length; m++) {
                                    if (TextUtils.equals(nextSpecId, skuSpecValArr[m].split(":")[0])) {
                                        //当前套餐中需要下一步选择的规格id
                                        String nextValId = skuSpecValArr[m].split(":")[1];
                                        Spec tmpSpec = mDataList.get(selectIndex + 1);//需要筛选的规格对象

                                        for (int p = 0; p < tmpSpec.getGoodsFeatureVals().size(); p++) {
                                            boolean isRepeat = false;
                                            if (null != nextValList && nextValList.size() > 0) {
                                                for (int q = 0; q < nextValList.size(); q++) {
                                                    if (TextUtils.equals(nextValId, nextValList.get(q).getId())) {
                                                        isRepeat = true;
                                                    }
                                                }
                                            }
                                            if (!isRepeat) {
                                                Spec.SpecDetail tmpVal = tmpSpec.getGoodsFeatureVals().get(p);
                                                if (TextUtils.equals(tmpVal.getId(), nextValId)) {//找到了需要的型号对象
                                                    nextValList.add(tmpVal);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        Logg.i("nextValList = " + nextValList.size());
                        mDataList.get(selectIndex + 1).setGoodsFeatureVals(nextValList);
                    }
                }

                StringBuffer sb = new StringBuffer("");
                for (int d = 0; d < mDataList.size(); d++) {
                    Spec s = mDataList.get(d);
                    for (int e = 0; e < s.getGoodsFeatureVals().size(); e++) {
                        Spec.SpecDetail v = s.getGoodsFeatureVals().get(e);
                        if (v.isSelected()) {
                            sb.append(v.getGoodsFeatureName() + "  ");
                        }
                    }
                }
                Arad.bus.post(new EventModel(18111951, sb.toString()));//选择的结果

                notifyDataSetChanged();
            }
        });
    }

    private class ValAdapter extends ListBaseAdapter<Spec.SpecDetail> {

        public ValAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.pro_item_spec_tag;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_tag_name = holder.getView(R.id.tv_tag_name);
            LinearLayout ll_item = holder.getView(R.id.ll_item);//item布局

            Spec.SpecDetail detail = mDataList.get(position);
            tv_tag_name.setText(detail.getGoodsFeatureName());
            if (detail.isSelected()) {
                ll_item.setSelected(true);
            } else {
                ll_item.setSelected(false);
            }
        }
    }
}
